import * as bcrypt from 'bcryptjs';
import log from '../../../helpers/logger';
import { pushDiscordWebhook } from '../../../helpers/pushDiscordWebhook';
import {
  AuthProvider,
  findOrCreateUser,
  isEmailFree,
} from '../../../services/uctoo/uctoo_user';
import { validateSignUp } from '../../../helpers/dataValidation';
import { defaultRouteHandler } from '../../../../interfaces';
import { connectUserHasGroup } from '../../../services/uctoo/user_has_group';
import { connectUserHasAccount } from '../../../services/uctoo/user_has_account';

import db from '../../../lib/db';
import { stat } from 'fs';

const handleResetpassword: defaultRouteHandler = async (req, res) => {
  try {
    log.info('handleResetpassword');
    const body = await req.json();
    log.info(body);
    const {user_id, name, username, email, password, repeat_password, verifyCode } = body;
    
    let account_id = null;   

      if (!verifyCode) {
        return res.status(400).json({ err: "42001", desc: "verify code is required" });
      }else{
        //通过user_id查询用户
        const user = await db.uctoo_user.findFirst({
          where: {
            id: user_id,
          },
        });
        //比对验证码是否一致
        if (user.status !== Number(verifyCode)) {
          return res.status(400).json({ err: "42002", desc: "verify code is invalid" });
        }

        let lUser = {
          password,
          status: 0,
        };
        await bcrypt.hash(password, 10).then((hash) => {
          lUser.password = hash;
        });
        //更新用户密码
        await db.uctoo_user.update({
          where: {
            id: user_id,
          },
          data: lUser,
        }); 
      }
    res.status(200).json({ code: "200", desc: "重置密码成功" });
  } catch (e) {
    log.error({ err: e.message, desc: e.response.data.error_description });
    res.status(500).json({ err: e.message, desc: e.response.data.error_description });
  }
};
export default handleResetpassword;
